// Functions

function $(id){return document.getElementById(id);}

// -- //

function showMore()
{	
    document.body.setAttribute('id', 'more');
}

function showLess()
{	
    document.body.setAttribute('id', 'less');
}

function didRotate(width)
{
	document.body.style.width = width + 'px';
}


// --- //

var androidVersion;

function loadSettings(fontSize, fontType, textAlign, textStyle, version)
{
	androidVersion = version;
	newFontSize(fontSize);
	newFontType(fontType);
	newTextAlign(textAlign);
	newTextStyle(textStyle);
	document.body.style.visibility = 'visible';
}

function newFontSize(i)
{
	var el;
	try{ el = saveScroll(); } catch(e){}
	
	document.body.style.fontSize = i + 'px';
	
	if (el) el.scrollIntoView(true);
}

function newFontType(i)
{
	document.body.setAttribute('fontType', i);
}

function newTextAlign(i)
{
	if (i == 1 && !document.body.className.match('A1'))
	{
		document.body.className += ' A1';
	}
	else
	{
		document.body.className = document.body.className.replace('A1', '');
	}
}

function newTextStyle(i)
{
	document.body.setAttribute('textStyle', i);
}


// --- //


var scrollTO;
var scrolledOnceBefore;
var lastY;
var lastI;
var lastSection;
var currentPosition;


function scrolled(e) {
	try{
		if (lastY != scrollY())
		{
			saveScroll();
		}
	}catch(e){/*alert(e);*/}
}

var currentM;
var currentH;
var currentY;
var currentI;
var currentSection;

function saveArticleScroll()
{
	ReadItLaterJSMethods.reportingScroll(currentM, currentH, currentY, currentI, currentSection);
	//return currentPosition;
}


function saveScroll() {
	try{	
		
		var win     = windowSize();
		var y       = scrollY();
		var tY      = androidVersion*1 >= 8 ? 20 : y; // 8 == FROYO 2.2
		var high 	= document.elementFromPoint(win[0]/2, tY);
		var low 	= document.elementFromPoint(win[0]/2, tY+25);
		var iH 		= high ? high.getAttribute('nodeIndex') : null;
		var iL 		= low ? low.getAttribute('nodeIndex') : null;
		
		var e, i;
		if (iH && iH*1 > iL*1) {
			e = high;
			i = iH;
		} else if (iL) {
			e = low;
			i = iL;	
		}
        
        //ReadItLaterJSMethods.log( y +','+ tY +','+ high.id+','+ low+','+ iH+','+ iL+','+ e+','+ i)
		
		if (i || y < 100) 
		{
			var m 	= document.body.scrollHeight;
			var h 	= win[1];
			//if (y > 100) 
			//{				
				currentM = m;
				currentH = h;
				currentY = y;
				currentI = i;
				currentSection = (document.body.id=='more'?1:0);
				
                //ReadItLaterJSMethods.log( currentM +','+ currentH +','+ currentY+','+ currentI+','+ currentSection)
				ReadItLaterJSMethods.reportingScroll(currentM*1, currentH*1, currentY*1, currentI*1, currentSection*1);
				//currentPosition = m+'|'+h+'|'+y+'|'+i+'|'+(document.body.id=='more'?1:0);
				
			//}
			lastI = i;
		}
        
        
		lastY = y;
		
		return e;
	}catch(e){
		ReadItLaterJSMethods.log('<BR>saveScroll ERROR ' + e);
	}
}

function scrollY() {
	var y=0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		y = window.pageYOffset;
	} else if( document.body && ( document.body.scrollTop ) ) {
		//DOM compliant
		y = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollTop ) ) {
		y = document.documentElement.scrollTop;
	}
	return y;
}

function windowSize() {
	var h = 0, w=0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		w = window.innerWidth;
		h = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientHeight ) ) {
		//IE 4 compatible
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	}
	return [w,h];
}

function firstElementWithAttributeValue(a, v) {
	var arrElements = document.getElementsByTagName('*');
	for(var i=0; i<arrElements.length; i++){
		av = arrElements[i].getAttribute(a);
		if (av && av == v) {
			return arrElements[i];
		}
	}
}

function scrollToLastI()
{
	scrollToNodeIndex(lastSection, lastI);
}

function scrollToNodeIndex(section, nodeIndex) 
{
	try
	{
		lastSection = section;
		// find first Element with attribute nodeIndex = i (make sure it's inside less or more based on view)
		var i, e, av, arrElements;
		var mode = section == 1 ? 'more' : 'less';
		
		arrElements = document.getElementById('RIL_'+mode).getElementsByTagName('*');
		for(i=0; i<arrElements.length; i++)
		{
			av = arrElements[i].getAttribute('nodeIndex');
			if (av && av == nodeIndex) 
			{
				e = arrElements[i];
				break;
			}
		}
		if (e)
		{
			document.body.setAttribute('id', mode);
			window.scrollTo(0,e.offsetTop);
			window.scrollTo(0,e.offsetTop);
		}
	}
	
	catch(e){/*alert(e);*/}
}



// -- //

var scale;
var isPad;
var needsLayout;
function loadImage(id,src,caption,credit,scale,isPad)
{
	try
	{
		scale = scale * 1;
		isPad = isPad;
		
		//saveScroll();
		
		$('RIL_IMG_'+id).innerHTML = '<a id="RIL_IMG_A_'+id+'" href="ISRIL:IMG||'+id+'" class="noLinkStyle"></a><caption>'+caption+' <cite>'+(credit?'Photo by: ':'')+credit+'</cite></caption>';
		
		if (caption.length || credit.length)
			$('RIL_IMG_'+id).className += ' hasCaption';
            
		//ReadItLaterJSMethods.log( 'loadImage: wrapper ' + $('RIL_IMG_'+id) );
		//ReadItLaterJSMethods.log( 'loadImage: inner ' + $('RIL_IMG_'+id).innerHTML );
			
		// good:
		var image = new Image();
		image.onload = function() 
		{
			try
			{
				/*
                ReadItLaterJSMethods.log( 'onLoadImage: this ' + this );
				ReadItLaterJSMethods.log( 'onLoadImage: src ' + this.src );                
				ReadItLaterJSMethods.log( 'onLoadImage: width ' + this.width );            
				ReadItLaterJSMethods.log( 'onLoadImage: parentNode ' + this.parentNode );            
				ReadItLaterJSMethods.log( 'onLoadImage: parentNodeparentNode ' + this.parentNode.parentNode );
                */
                
				//resize for scale
				if (scale > 1)
					this.width *= (1.0 / scale);
		
				
				
				var wrapper = this.parentNode.parentNode;
				wrapper.style.width = (this.width>175?this.width:175) + 'px';
				wrapper.className += ' loaded ';
				
				if (wrapper.parentNode.nodeName == 'A' && !wrapper.parentNode.href.match('ISRIL:'))
				{
					wrapper.parentNode.href =
					this.parentNode.href = 'ISRIL:LINKIMG||'+id+'||'+wrapper.parentNode.href;
				}
				
				// iPad floating
				if (isPad && this.width / $('RIL_container').offsetWidth <= 0.6)
					wrapper.setAttribute('float', 1);
				
				else if (isPad)
					wrapper.setAttribute('float', 0);
				
				//scrollToLastI();
                
                needsLayout = true;
                
				//ReadItLaterJSMethods.log( 'onLoadImageEnded ' );
			}
			catch(e)
			{
				ReadItLaterJSMethods.log( 'onLoadImageError: ' + e );
			}
		}
		
		image.src = src + '?nocache=' + (Math.random()*10000000);
		$('RIL_IMG_A_'+id).appendChild(image);
	
	}
	catch(e)
	{
		ReadItLaterJSMethods.log( 'loadImageError: ' + e );
	}
}
//alert(id+" | "+src+" | "+type+" | "+vid+" | "+isPad);

function loadVideo(id,src,type,vid,isPad)
{
    //try {
    
    var embed;
    var width = 280;
    var height = 235;
    
    if (!ReadItLaterJSMethods.isConnected())
        embed = '<a style="width:'+width+'px;height:'+height+'px;" href="javascript:alert(\'Offline video is not supported at this time.  Please connect to the internet to view this video.\')"> </a>';

    else
    {
            
        //VIDEO_YOUTUBE
        if (type == '1')
        {
            var movie = type == '1' ? 'http://www.youtube.com/v/'+vid : src;
            embed = "\
            <object align='center' width='"+width+"' height='"+height+"'>\
            <param value='"+movie+"' name='movie'>\
            <param value='transparent' name='wmode'>\
            <embed width='"+width+"' height='"+height+"' wmode='transparent' type='application/x-shockwave-flash' src='"+movie+"'>\
            </object>"
        }
        
        // VIDEO_VIMEO_LINK | VIDEO_VIMEO_MOOGALOOP | VIDEO_VIMEO_IFRAME
        else if (type == '2' || type == '3' || type == '4')
        {
            var movie = 'http://player.vimeo.com/video/'+vid+'?title=0&amp;byline=0&amp;portrait=0';
            embed = '<iframe width="'+width+'" height="'+height+'" frameborder="0" src="'+src+'"></iframe>';
        }
        
        // VIDEO_HTML5
        else if (type == '5')
        {
            embed = "<video align='center' id='v' autoplay width='"+width+"' height='"+height+"' controls='controls' src='"+movie+"' tabindex='0'></video>";
        }
        
        // VIDEO_FLASH
        else if (type == '6')
        {
            if (androidVersion*1 >= 8)
            {
                embed = "\
                <object align='center' width='"+width+"' height='"+height+"'>\
                <param value='"+src+"' name='movie'>\
                <param value='transparent' name='wmode'>\
                <embed width='"+width+"' height='"+height+"' wmode='transparent' type='application/x-shockwave-flash' src='"+src+"'>\
                </object>";
            }
            
            else
                embed = '<a style="width:'+width+'px;height:'+height+'px;" href="javascript:alert(\'This video uses Abode Flash and is not supported by your device.\')"> </a>';
        }
        
    }
    
    saveScroll();
    $('RIL_VIDEO_'+id).innerHTML = embed;
    scrollToLastI();
    
    needsLayout = true;
    //}catch(e){alert(id+'|'+e);}
}


function showImageUpsell()
{
	//try{
	if (!$('RIL_ARTICLE_NOTE'))
	{
		var upsell = document.createElement('a');
		upsell.href = 'ISRIL:PRO';
		upsell.id = 'RIL_TEXT_UPSELL';
		upsell.innerHTML = '<img src="inReaderUpsellText@2x.png" width="112" /><span>Get Read It Later Pro to view images and video in the Article View!<br /><u>Go Pro »</u></span>';	
		$('RIL_less').insertBefore( upsell, $('RIL_less').firstChild );
		return '1';
	}
	//}catch(e){alert(e);}
}

function relayout(i)
{     
	document.getElementById('RIL_container').style.padding = '0px 0px '+(Math.random()*2)+'px 0px';    
	
	if (!needsToBeRedrawn())
    	clearInterval(layoutTO);
}

function needsToBeRedrawn()
{
	//ReadItLaterJSMethods.log( 'height : ' + ReadItLaterJSMethods.getScrollableHeight() + ' | ' + document.body.scrollHeight);
	if (needsLayout // an image was loaded
		&& ReadItLaterJSMethods.getScrollableHeight() != document.body.scrollHeight)
	{
		return true;
	}
}


// -- //

try
{
	
	var ua = navigator.userAgent;
	var yHitMethod;
	if (ua.match(/Firefox/) || ua.match(/IE/)) {
		yHitMethod = 'screen';
	} else {
		yHitMethod = 'page';
	}	


	// -- Init
	
	
	var o = {};	
    var layoutTO;
	
	window.onload = function()
	{
		
		//ReadItLaterJSMethods.log( 'window.onload' );
        		
		try
		{
			
			setInterval(scrolled, 500);	
            
            // watch for scroll
			document.addEventListener('scroll', scrolled, false);
            
            document.addEventListener('scroll', function()
            {
                //ReadItLaterJSMethods.log( 'SCROLLED' );
                if (needsToBeRedrawn())
                {
                    clearInterval(layoutTO);
                    layoutTO = setInterval(function()
                    {
                        //ReadItLaterJSMethods.log( 'go relayout' );
                        ReadItLaterJSMethods.readerNeedsLayout();
                    }, 100);
                }
            }, false);
            
			
			if ($('nav_more'))
			{
				if ($('RIL_settings'))
					$('RIL_settings').onclick = function(){window.location='ISRIL:TEXT-SETTINGS';};
				
				$('nav_more').getElementsByTagName('a')[0].onclick = showMore;
				$('nav_less').getElementsByTagName('a')[0].onclick = showLess;
				
				// look for a bad less section
				
				if ( $('RIL_less').textContent.length  < 200 ) {
					var p = document.createElement('p');
					p.className = 'note';
					p.innerHTML = 'The text generator could not find much content.  You might have better luck switching to the \'More\' view. </p><p>  If you know there <em>should</em> be an article here, help improve the text view by	<a href=\'http://ideashower.com/support/read-it-later/report-pages-not-saving-well-offline-here/\'>reporting this page</a>.  Thanks!</p>';
					$('RIL_less').insertBefore(p,$('RIL_less').firstChild);
				}
				if ( $('RIL_more').textContent.length  < 200 ) {
					var p = document.createElement('p');
					p.className = 'note';
					p.innerHTML = 'The text generator could not find much content.  If you know there <em>should</em> be an article here, help improve the text view by	<a href=\'http://ideashower.com/support/read-it-later/report-pages-not-saving-well-offline-here/\'>reporting this page</a>.  Thanks!</p>';
					$('RIL_more').insertBefore(p,$('RIL_more').firstChild);
				}
			}
			
			// update scheme links
			for(var i in document.links)
			{
				if (document.links[i] && document.links[i].href && document.links[i].href.match('isril:'))
				{
					document.links[i].onclick = document.links[i].href.match(':less') ? showLess : showMore;
					document.links[i].removeAttribute('href');					
				}
			}
			
			if ( $('RIL_no_less_view_note') )
			{
				showMore();
			}
			
			// update galleries
			galleries = document.getElementsByAttribute('isGallery', '1');
			for(var i=0; i<galleries.length; i++)
			{
				var clearer = document.createElement('div');
				clearer.className = 'RIL_clear';
				galleries[i].appendChild(clearer);
			}
		}
		
		catch(e){alert(e);}
	}
	
	document.getElementsByAttribute = function( attrib, value, context_node, tag ) {
			var nodes = [];
			if ( context_node == null )
				context_node = this;
			if ( tag == null ) 
				tag = '*';
			var elems = context_node.getElementsByTagName(tag);
			
			for ( var i = 0; i < elems.length; i += 1 ) {
				if ( value ) {
					if ( elems[i].hasAttribute(attrib) && elems[i].getAttribute(attrib) == value )
						nodes.push(elems[i]);
				} else {
					if ( elems[i].hasAttribute(attrib) )
						nodes.push(elems[i]);
				}
			}
			return nodes;
	}
	
	
}

catch(e){/*alert(e);*/}




